import React, {PureComponent} from 'react';
import {
    PAGE_TEN,
    TABLE,
    COMMON_TABLE_EMPTY_TEXT,
    PAGINATION_OPTIONS_EXTEND,
    COMMON_TABLE_QUERY_FAIL_TEXT,
    ROWSELECTION_FIXED_COLUMN_WIDTH,
} from '../constants';
import styles from './style.css';
import PropTypes from 'prop-types';
import {conventSorter} from './utils';
import {injectIntl, formatMessage} from './intl';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {Table, Card, Row, Col, Affix, Alert, message} from 'antd';
export class TablePanel extends PureComponent {
    state = {
        loading: false,
        selectedRowKeys: [],
        selectedRows: [],
    };
    static getDerivedStateFromProps(props, state) {
        if(props.data !== state.prevData)
            return {
                prevData: props.data,
                selectedRowKeys: [],
                selectedRows: []
            };
        return null;
    }
    affixOnChange = () => this.forceUpdate();
    onClickBatchDel = () => {
        const selectIds = this.state.selectedRowKeys;
        if(selectIds.length === 0)
            message.warning(formatMessage({
                id: 'tablePanel.btn.ValidationMessage',
                defaultMessage: '请选择需要批量操作的单据'
            }));
        else {
            this.setState({loading: true});
            this.props.selectDel(this.state.selectedRows.map(v => ({
                id: v.id,
            }))).then(() => {
                this.setState({
                    loading: false
                });
            });
        }
    }
    onChangeSort = (pagination, filters, sorter) => {
        if(pagination.current - 1 === this.props.pageIndex && pagination.pageSize === this.props.pageSize)
            this.props.onChangeSort({...conventSorter(sorter),
                pageIndex: PAGE_TEN.index});
    };
    onEndBatchOperation = () => {
        this.setState({
            selectedRowKeys: [],
            selectedRows: []
        });
        this.props.onEndBatchOperation();
    }
    onSelectedChange = (rkeys, keys) => {
        this.setState({
            selectedRowKeys: rkeys,
            selectedRows: keys
        });
    };
    render() {
        const {pageIndex, pageSize, total, isShowBatchDelPanel} = this.props;
        const rowSelection = isShowBatchDelPanel ? {
            fixed: true,
            type: 'checkbox',
            columnWidth: ROWSELECTION_FIXED_COLUMN_WIDTH,
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: this.onSelectedChange
        } : undefined;
        const columns = [{
            title: formatMessage({
                id: 'tablePanel.column.dealerCode',
                defaultMessage: '总代号'
            }),
            dataIndex: 'dealerCode',
            sorter: true
        }, {
            title: formatMessage({
                id: 'tablePanel.column.partCode',
                defaultMessage: '备件号'
            }),
            dataIndex: 'partCode',
            sorter: true
        }, {
            title: formatMessage({
                id: 'tablePanel.column.partName',
                defaultMessage: '备件名称'
            }),
            dataIndex: 'partName'
        }];
        const batchDeleteMessage = (<Row>
            <Col span={18}>{
                formatMessage({
                    id: 'tablePanel.Validation.Message',
                    defaultMessage: '正在进行批量操作，点击右侧关闭将退出操作'
                })
            }</Col>
            <Col span={6} className="col-align-right">
                <WrappedPopconfirm
                    key="batchMerge"
                    placement="topRight"
                    onConfirm={this.onClickBatchDel}
                    id="batchMerge"
                    title={formatMessage({
                        id: 'tablePanel.message.batchDelete',
                        defaultMessage: '是否确认批量删除？'
                    })}>
                    <a className={styles.panelalertMessage}>{formatMessage({
                        id: 'tablePanel.operation.batchDelete',
                        defaultMessage: '批量删除'
                    })}</a>
                </WrappedPopconfirm>
            </Col>
        </Row>);
        const pagination = {
            total,
            pageSize,
            current: pageIndex + 1,
            onShowSizeChange: this.props.onPageSizeChange,
            onChange: this.props.onPageIndexChange,
            ...PAGINATION_OPTIONS_EXTEND
        };
        const locale = {
            emptyText: this.props.hasError ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        return (
            <Card>
                {isShowBatchDelPanel && <Affix offsetTop={0} className={styles.alertMargin} onChange={this.affixOnChange}>
                    <Alert message={batchDeleteMessage} type="warning" closable showIcon
                        closeText={<span className={styles.closeText}>{formatMessage({
                            id: 'tablePanel.btn.close',
                            defaultMessage: '关闭'
                        })}</span>} onClose={this.onEndBatchOperation} />
                </Affix>}
                <Table
                    className="white-space-nowrap"
                    columns={columns}
                    dataSource={this.props.data}
                    rowKey="id"
                    pagination={pagination}
                    rowSelection={rowSelection}
                    loading={this.props.loading || this.state.loading}
                    onChange={this.onChangeSort}
                    locale={locale}
                    {...TABLE}/>
            </Card>
        );
    }
}

TablePanel.propTypes = {
    data: PropTypes.array.isRequired,
    hasError: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    onEndBatchOperation: PropTypes.func.isRequired,
    onPageIndexChange: PropTypes.func.isRequired,
    onPageSizeChange: PropTypes.func.isRequired,
    intl: PropTypes.object,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
};
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {tableSearch, onSelectDel, clearBatchData, querySearch} from './actions';
const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const mapStateToProps = state => ({
    data: getData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    hasError: state.getIn(['page', 'domainData', 'list', 'hasError']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    isShowBatchDelPanel: state.getIn(['page', 'ui', 'showBatchDelPanel']),
});

const mapDispatchToProps = dispatch => ({
    onPageSizeChange: (current, pageSize) =>
        dispatch(
            tableSearch({
                pageIndex: PAGE_TEN.index,
                pageSize
            })
        ),
    onPageIndexChange: pageIndex =>
        dispatch(
            tableSearch({
                pageIndex: pageIndex - 1
            })
        ),
    onChangeSort: option => dispatch(tableSearch(option)),
    onEndBatchOperation: () => dispatch(clearBatchData()),
    selectDel: value =>
        dispatch(onSelectDel(value)).then(success => {
            if(success) {
                dispatch(querySearch());
                dispatch(clearBatchData());
            }
            return success;
        }),
});
import {connect} from 'react-redux';
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));
